#include "SimpleTipCtrl.h"
#include <string.h>

CSimpleTipCtrl::CSimpleTipCtrl()
{
   m_pszText = NULL;
   m_sizeText.cx = 0;
   m_sizeText.cy = 0;
   m_brBack = CreateSolidBrush(DEFAULT_TIP_BKCOLOR);
   m_nHMargin = DEFAULT_TIP_MARGIN;
   m_nVMargin = DEFAULT_TIP_MARGIN;
}

CSimpleTipCtrl::~CSimpleTipCtrl()
{
   if (m_pszText) {
      delete [] m_pszText;
   }
   if (m_brBack) {
      DeleteObject(m_brBack);
   }
}

int CSimpleTipCtrl::SetText(const POINT* ptScr, LPCTSTR txt)
{
   assert (::IsWindow(m_hWnd));

   if (m_pszText) {
      delete [] m_pszText;
      m_pszText = NULL;
   }

   if (!txt) {
      ShowWindow(SW_HIDE);
      return 0;
   }

   m_pszText = new TCHAR [_tcslen(txt) + 1];
   if (!m_pszText) {
      ShowWindow(SW_HIDE);
      return -1;
   }
   _tcscpy(m_pszText, txt);

   CalcTextSize(m_pszText, &m_sizeText);
   RECT rc;
   rc.left = ptScr->x;
   rc.top = ptScr->y;
   rc.right = rc.left + m_sizeText.cx;
   rc.bottom = rc.top + m_sizeText.cy;
   MoveWindow(&rc, TRUE);
   ShowWindow(SW_SHOW);
   Invalidate();
   return 0;
}

void CSimpleTipCtrl::CalcTextSize(LPCTSTR txt, SIZE* size)
{
   assert (txt);
   assert (size);

   if (!::IsWindow(m_hWnd)) {
      size->cx = 0;
      size->cy = 0;
      return;
   }

   HDC hdc = GetDC();
   int len = _tcslen(txt);
   GetTextExtentPoint32(hdc, txt, len, size);
   size->cx += m_nHMargin * 2;
   size->cy += m_nVMargin * 2;
   ReleaseDC(hdc);
}

void CSimpleTipCtrl::SetBkgrdColor(COLORREF clrBk)
{
   if (m_brBack) {
      DeleteObject (m_brBack);
   }
   m_brBack = CreateSolidBrush(clrBk);
}

LRESULT CSimpleTipCtrl::OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
   if (!m_pszText) {
      ShowWindow(SW_HIDE);
      return 0;
   }

   CalcTextSize(m_pszText, &m_sizeText);
   RECT rcWnd;
   GetWindowRect(&rcWnd);
   rcWnd.right = rcWnd.left + m_sizeText.cx + m_nHMargin*2 + 2; // 2 is for the board
   rcWnd.bottom = rcWnd.top + m_sizeText.cy + m_nVMargin*2 + 2;
   MoveWindow(&rcWnd, false);
   ShowWindow(SW_SHOW);
   UpdateWindow();
   return 0;
}

LRESULT CSimpleTipCtrl::OnPaint(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
   PAINTSTRUCT ps;
   BeginPaint(&ps);
   
   RECT rc;
   GetClientRect(&rc);

   HDC hdc = ps.hdc;
   FillRect(hdc, &rc, m_brBack);

   SetTextAlign(hdc, TA_CENTER | TA_TOP);
   SetBkMode(hdc, TRANSPARENT);
   if (m_pszText) {
      TextOut(hdc, (rc.right - rc.left)/2, rc.top + m_nVMargin, m_pszText, _tcslen(m_pszText));
   }
   EndPaint(&ps);
   return 0;
}
